package com.recipe.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.recipe.entity.RecommendDish;
import com.recipe.util.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author lzk
 * @date 2024-06-19 08:57:21
 * @description
 */
@Service
@Slf4j
@SuppressWarnings("all")

public class Recommend {

    private static final String ApiKey="sk-fe57d83027b044a9938785a65b438f16";
    public RecommendDish recommendRecipe(String keyword) {
        long start = System.currentTimeMillis();

        JSONObject jsonData = new JSONObject();
        jsonData.put("model", "qwen1.5-110b-chat");
        JSONObject input = new JSONObject();
        JSONObject message2 = new JSONObject();
        message2.put("role", "user");

        String dish = String.format("根据以下关键字生成一个食谱 %s 并按照数据结构返json数据{\"foodName\":\"分类名称\",\"foodSource\":\"原料\",\"foodCook\":\"做法\"}", keyword);
        log.info("dish {}", dish);
        message2.put("content", dish);
        input.put("messages", new JSONObject[]{message2});
        jsonData.put("input", input);
        jsonData.put("parameters", new JSONObject());


        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("Authorization", "Bearer " + ApiKey);
        headerMap.put("Content-Type", "application/json");
        headerMap.put("X-DashScope-SSE", "enable");

        String url = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation";
        String body = HttpUtils.executePost(url, jsonData.toJSONString(), headerMap);
        System.out.println(body);

        int index = body.lastIndexOf("data:");
        String substring = body.substring(index + 5, body.length() - 1);
        JSONObject jsonObject = JSONObject.parseObject(substring);
        String text = jsonObject.getJSONObject("output").getString("text");
        int jsonIndex = text.lastIndexOf("```json");
        String json = text.substring(jsonIndex + 8, text.lastIndexOf("```"));
         RecommendDish recommendDish= JSONObject.parseObject(json, RecommendDish.class);
        log.info("cost {} data:{}", System.currentTimeMillis() - start, JSON.toJSONString(recommendDish));

        return recommendDish;

    }




}

